<?php
declare (strict_types=1);

namespace app\common\model;

/**
 * @mixin \think\Model
 */
class Account extends Base
{

    protected $name = 'user_account';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile');
    }

    public function take()
    {
        return $this->hasOne(User::class, 'id', 'source')->field('id,code,nickname,mobile');
    }

    public function getTypeAttr($value)
    {
        return get_pay_way($value);
    }


    public static function _adds($id, $type, $amount, $intros, $fx, $source = 0, $category = 0, $is_grant = 2, $is_bonus = 0, $is_user = 0)
    {
        try {

            if (is_array($intros)) {
                $intro = $intros[0];
                $msg = $intros[1];
            } else {
                $intro = $intros;
                $msg = '';
            }
            $assets = Assets::where('uid', $id)->find();
            $after = $fx == '+' ? floatval($assets->$type) + floatval($amount) : floatval($assets->$type) - floatval($amount);
            parent::create([
                'uid'         => $id,
                'type'        => $type,
                'intro'       => $intro,
                'amount'      => $amount,
                'front'       => $assets->$type,
                'after'       => $after,
                'fx'          => $fx,
                'create_time' => time(),
                'create_date' => date('Y-m-d'),
                'source'      => $source,
                'category'    => $category,
                'is_grant'    => $is_grant,
                'is_bonus'    => $is_bonus,
                'is_user'     => $is_user,
                'is_admin'    => $intro == '后台充值' || $intro == '后台充值' ? 1 : 0,
                'msg'         => $msg
            ]);

            $assets->$type = $after;
            $assets->save();
            return true;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }


}
